package me.rjy.second.screen.demo

import android.app.ActivityOptions
import android.app.AlertDialog
import android.app.Presentation
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
import android.os.Bundle
import android.view.Display
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import me.rjy.second.screen.demo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private var presentation: Presentation? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btActivity.setOnClickListener {
            showDisplaySelectDialog {
                startActivity(
                    Intent(this, SecondDisplayActivity::class.java).apply {
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    },
                    ActivityOptions.makeBasic().apply {
                        setLaunchDisplayId(it.displayId)
                    }.toBundle()
                )
            }
        }

        binding.btPresentation.setOnClickListener {
            if (presentation == null || presentation?.isShowing != true) {
                showDisplaySelectDialog {
                    presentation = SecondScreenPresentation(this, it).apply {
                        show()
                    }
                }
            } else {
                presentation?.dismiss()
                presentation = null
            }
        }
    }

    private fun showDisplaySelectDialog(callback: (Display)->Unit) {
        val dialogView = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }
        var dialog: AlertDialog? = null
        (getSystemService(Context.DISPLAY_SERVICE) as DisplayManager).displays.forEach { display ->
            dialogView.addView(Button(this).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                text = "${display.name}[${display.displayId}]"
                setOnClickListener {
                    dialog?.dismiss()
                    callback.invoke(display)
                }
            })
        }

        dialog = AlertDialog.Builder(this).setTitle("切换环境").setView(dialogView).show()
    }
}
